﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Net.Http;
using System.Net.Http.Formatting;
using ScrumFactory.Extensions;


namespace ScrumFactory.Services.Clients.AuthProviders {


    [Export(typeof(IAuthorizationProviderService))]
    public class WindowsAuthorizationProviderClient : IAuthorizationProviderService {

        [Import(typeof(IServerUrl))]
        private IServerUrl serverUrl { get; set; }

        [Import("WindowsAuthorizationServiceUrl")]
        private string serviceUrl { get; set; }

        private Uri Url(string relative) {
            return new Uri(serviceUrl.Replace("$ScrumFactoryServer$", serverUrl.Url) + relative);
        }


        public string ProviderName {
            get { return "Windows Authentication"; }
        }

        public string ProviderImageUrl {
            get {
                return @"\Images\AuthorizationProviders\WindowsLogo.png";
            }
        }
        
        public string GetAuthorizationToken(string user, string password) {

            if (string.IsNullOrEmpty(user))
                return null;

            user = user.Replace("\\", "@@");

            var client = ServiceClient.GetClient();
            
            HttpResponseMessage response = null;
            response = client.Post(Url("WindowsAuthorization/" + user), new ObjectContent<string>(password, JsonMediaTypeFormatter.DefaultMediaType));
            

            if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                return null;

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new ScrumFactory.Exceptions.ScrumFactoryException("Error getting authorization token");

            
            
            return response.Content.ReadAs<string>();

        }

        public bool ValidadeToken(string token, string user) {
            throw new System.NotSupportedException();
        }

        public bool PasswordRequired {
            get {
                return true;
            }
        }

        public bool IsNetworkUser {
            get {
                return true;
            }
        }

        
    }
}
